package com.hxhy.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.aisino.bean.Electronic;
import com.aisino.bean.ElectronicDetail;
import com.aisino.utils.FPInfo;
import com.aisino.utils.ResultInfo;
import com.aisino.webs.FPServiceAPI;
import com.hxhy.bean.Account;
import com.hxhy.bean.BElectronic;
import com.hxhy.bean.ElectronicException;
import com.hxhy.util.Tools;

/**
 * 西安一体化(陕西省电子发票)
 */
@Service("xayth")
public class InvoiceServiceImpl1 extends InvoiceServiceImpl implements InvoiceService {

	@Override
	public void init() {
		super.init();
	}

	@Override
	public BElectronic kpInvoice(BElectronic be) throws ElectronicException {
		return null;
	}

	@Override
	public BElectronic hpInvoice(BElectronic be) throws ElectronicException {
		BElectronic yfp = mapper.getInvoiceByFPH(be.getInvoicenum(), be.getInvoiceversion(), "正票", "电子发票");
		if (yfp == null) {
			be = error(be, "未查询到票据信息");
			throw new ElectronicException(be);
		}

		yfp.setFlag("2");
		mapper.update(yfp);

		Electronic e = Electronic.hpInvoice(yfp);
		if (e == null) {
			error(be, "内部数据错误");
			throw new ElectronicException(be);
		}

		be.setAccountids("-1");
		be.setHouseid(yfp.getHouseid());
		be.setTel(yfp.getTel());
		be.setMoney(BigDecimal.ZERO.subtract(yfp.getMoney()));
		be.setCardno(yfp.getCardno());
		be.setEmail(yfp.getEmail());
		be.setGfmc(yfp.getGfmc());
		be.setNsrsbh(yfp.getNsrsbh());
		be.setKhh(yfp.getKhh());
		be.setDz(yfp.getDz());
		be.setInvoicemethod(yfp.getInvoicemethod());
		be.setInvoicekind("负票");
		be.setLsh(yfp.getLsh());
		be.setInvoicenum(null);
		be.setInvoiceversion(null);
		be.setReverselsh(yfp.getLsh());
		be.setKpr(yfp.getKpr());
		be.setSkr(yfp.getSkr());
		be.setFhr(yfp.getFhr());
		be.setReturncode("0000");
		be.setReturnstate(null);
		be.setFlag("1");
		int i = mapper.insert(be);

		if (i != 1) {
			error(be, "内部数据错误");
			throw new ElectronicException(be);
		}

		log.info("红冲发票: " + e.get());
		mapper.log(be.getLsh(), "1", e.get());
		ResultInfo info = new FPServiceAPI().getFPServiceAPIHttpPort().createUser(e.get());
		log.info(info.getMessage().getValue());
		if ("0000".equals(info.getCode().getValue())) {
			be.setReturncode("0000");
			be.setReturnstate("开票中");
		} else {
			be.setReturncode(info.getCode().getValue());
			be.setReturnstate(FPInfo.getInstance(info.getMessage().getValue()).getRETURN_MESSAGE());
			mapper.update(be);
			yfp.setFlag("0");
			mapper.update(yfp);
		}

		return be;
	}

	@Override
	public BElectronic zfInvoice(BElectronic be) throws ElectronicException {
		return null;
	}

	@Override
	public BElectronic sendInvoice(BElectronic be) throws ElectronicException {
		return null;
	}

	@Override
	public void searchInvoice() {
		Electronic kp = null;
		try {
			List<BElectronic> list = mapper.kpList();
			for (BElectronic map : list) {
				BElectronic yfp = null;
				map.setAccountids(map.getAccountids().replaceAll(",null", "").replaceAll("null,", ""));
				if ("负票".equals(map.getInvoicekind())) {
					yfp = mapper.getInvoiceByLSH(map.getReverselsh(), "正票");
					if (yfp == null) {
						error(map, "未查询到蓝字发票");
						mapper.update(map);
						continue;
					}
					yfp.setAccountids(yfp.getAccountids().replaceAll(",null", "").replaceAll("null,", ""));
				}

				kp = new Electronic();
				kp.setDdbh(Tools.toString(map.getLsh()));
				kp.setIs_apply("负票".equals(map.getInvoicekind()) ? "4" : "2");
				kp = Electronic.spInvoice(kp);
				ResultInfo info = new FPServiceAPI().getFPServiceAPIHttpPort().createUser(kp.get());
				FPInfo fp = FPInfo.getInstance(info.getMessage().getValue());
				if (!"0011".equals(fp.getRETURN_CODE()) && !"1001".equals(fp.getRETURN_CODE())) {
					if ("负票".equals(map.getInvoicekind())) {
						map.setReverselsh(yfp.getLsh());

					}
					map.setInvoiceversion(fp.getFPDM());
					map.setInvoicenum(fp.getFPHM());
					map.setYzm(fp.getINVOICE_CHECK_CODE());
					map.setPdfpath("负票".equals(map.getInvoicekind()) ? fp.getPDF_RED_URL() : fp.getPDF_URL());
					map.setReturncode(fp.getRETURN_CODE());
					map.setReturnstate(fp.getRETURN_MESSAGE());
					if ("负票".equals(map.getInvoicekind()) && "0000".equals(fp.getRETURN_CODE())) {
						map.setFlag("1");
						yfp.setFlag("1");
						mapper.update(yfp);
						mapper.clearInvoiceById(yfp.getAccountids());
					}
					mapper.update(map);

					if (!Tools.isNullOrEmpty(map.getAccountids()))
						mapper.replaceInvoice(map);
				}
			}
		} catch (Exception e) {
			log.info(Tools.getErrorException(e));
		}
	}

	/**
	 * 定时开票
	 */
	@Override
	public void kp() {
		try {
			List<BElectronic> list = mapper.ykpList();
			for (BElectronic fp : list) {
				fp.setReturncode("0000");
				if (Tools.isNullOrEmpty(fp.getAccountids())) {
					fp.setAccountids("-1");
				}
				fp.setAccountids(fp.getAccountids().replaceAll(",null", "").replaceAll("null,", ""));
				// 过滤重复开票信息
				int n = mapper.fpCount(fp.getAccountids());
				if (0 < n) {
					error(fp, "账目信息已开发票");
					mapper.update(fp);
					continue;
				}
				if ("负票".equals(fp.getInvoicekind())) {
					BElectronic yfp = mapper.getInvoiceByFPH(fp.getInvoicenum(), fp.getInvoiceversion(), "正票",
							fp.getInvoicemethod());
					if (yfp == null) {
						error(fp, "未查询到蓝字发票");
						mapper.update(fp);
						continue;
					}
					fp.setLsh(yfp.getLsh());
					fp.setReverselsh(yfp.getLsh());
					fp.setHouseid(yfp.getHouseid());
					fp.setMoney(BigDecimal.ZERO.subtract(yfp.getMoney()));
					fp.setEmail(yfp.getEmail());
					fp.setGfmc(yfp.getGfmc());
					fp.setNsrsbh(yfp.getNsrsbh());
					fp.setDz(yfp.getDz());
					BElectronic be = new BElectronic();
					be.setLsh(yfp.getLsh());
					Electronic e = Electronic.hpInvoice(be);
					if (e != null) {
						log.info("自动开票:" + e.get());
						mapper.log(be.getLsh(), "1", e.get());
						ResultInfo info = new FPServiceAPI().getFPServiceAPIHttpPort().createUser(e.get());
						log.info(info.getMessage().getValue());
						if (!"0000".equals(info.getCode().getValue())) {
							fp.setReturncode(info.getCode().getValue());
							FPInfo fpxx = FPInfo.getInstance(info.getMessage().getValue());
							fp.setReturnstate(fpxx.getRETURN_MESSAGE());
						}
					}
				} else {
					if (Tools.isNullOrEmpty(fp.getGfmc())) {
						error(fp, "缺少参数发票抬头");
						mapper.update(fp);
						continue;
					}
					if (Tools.isNullOrEmpty(fp.getCardno())) {
						error(fp, "缺少开票类型");
						mapper.update(fp);
						continue;
					}
					List<Account> acts = null;
					if (99 > fp.getAccountids().split(",").length)
						acts = mapper.getFpAccount(fp.getAccountids());
					else
						acts = mapper.getFpAccountGroup(fp.getAccountids());
					if (0 == acts.size()) {
						error(fp, "获取开票账目信息失败,请检查账目信息");
						mapper.update(fp);
						continue;
					}
					Electronic e = new Electronic();
					fp.setLsh(e.getDdbh());
					if (!Tools.isNullOrEmpty(fp.getGfmc()))
						e.setGhfmc(fp.getGfmc());
					if (!Tools.isNullOrEmpty(fp.getNsrsbh()))
						e.setGhf_nsrsbh(fp.getNsrsbh());
					if (!Tools.isNullOrEmpty(fp.getDz()))
						e.setGhf_dz(fp.getDz());
					if (!Tools.isNullOrEmpty(fp.getTel()))
						e.setGhf_sj(fp.getTel());
					if (!Tools.isNullOrEmpty(fp.getEmail()))
						e.setGhf_email(fp.getEmail());
					if (!Tools.isNullOrEmpty(fp.getCardno()))
						e.setGhfqylx("个人".equals(fp.getCardno()) ? "03" : "01");
					e.setBz(fp.getRemark());
					List<ElectronicDetail> eds = new ArrayList<ElectronicDetail>();
					e.setKpxm(eds);
					for (Account ac : acts) {
						ElectronicDetail ed = new ElectronicDetail();
						ed.setXmmc(Tools.toString(ac.getAreaname()));
						ed.setXmdw("平方米");
						ed.setHsbz(isdutyfree(ac) ? "0" : "1");
						ed.setFphxz("0");
						ed.setXmdj(ac.getPrice());
						ed.setGgxh(ac.getAnnual().concat("供暖季"));
						ed.setSpbm("1100102010100000000");
						ed.setYhzcbs(isdutyfree(ac) ? "1" : "0");
						ed.setLslbs(isdutyfree(ac) ? "1" : "");
						ed.setZzstsgl(isdutyfree(ac) ? "免税" : "");
						ac.setReceivedsum(ac.getReceived());
						if (!isdutyfree(ac)) {
							ac.setReceivedsum(ac.getReceived().divide(BigDecimal.ONE.add(taxrate(ac)), 2,
									BigDecimal.ROUND_HALF_UP));
						}
						ed.setXmje(ac.getReceivedsum());
						ed.setKce(isdutyfree(ac) ? ac.getReceived() : BigDecimal.ZERO);
						ed.setSl(taxrate(ac));
						ed.setSe(ac.getReceived().subtract(ac.getReceivedsum()));
						eds.add(ed);
					}
					boolean b = e.kpInvoice();
					fp.setMoney(e.getKphjje());
					fp.setKpr(e.getKpy());
					fp.setSkr(e.getSky());
					fp.setFhr(e.getFhr());
					if (b) {
						log.info("自动开票:" + e.get());
						mapper.log(fp.getLsh(), "0", e.get());
						ResultInfo info = new FPServiceAPI().getFPServiceAPIHttpPort().createUser(e.get());
						log.info(info.getMessage().getValue());
						if (!"0000".equals(info.getCode().getValue())) {
							fp.setReturncode(info.getCode().getValue());
							FPInfo fpxx = FPInfo.getInstance(info.getMessage().getValue());
							fp.setReturnstate(fpxx.getRETURN_MESSAGE());
						}
					} else {
						fp.setReturncode("9999");
						fp.setReturnstate(e.get());
					}
				}
				mapper.update(fp);
			}
		} catch (Exception e) {
			log.info(Tools.getErrorException(e));
		}
	}

}
